package com.skynet.supervision.config;

import cn.hutool.core.util.ObjectUtil;
import com.skynet.supervision.utils.Strings;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.io.ResourceUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.naming.ConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Configuration
public class ShiroConfig {

    /**
     * 缓存管理器
     */
    @Bean
    public EhCacheManager getEhCacheManager() {
        net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("skynet");
        EhCacheManager em = new EhCacheManager();
        if (ObjectUtil.isNull(cacheManager)) {
            em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream()));
        } else {
            em.setCacheManager(cacheManager);
        }
        return em;
    }

    /**
     * 返回配置文件流 避免ehcache配置文件一直被占用，无法完全销毁项目重新部署
     */
    @SneakyThrows
    protected InputStream getCacheManagerConfigFileInputStream() {
        String configFile = "classpath:ehcache/ehcache-shiro.xml";
        InputStream inputStream = null;
        try {
            inputStream = ResourceUtils.getInputStreamForPath(configFile);
            byte[] b = IOUtils.toByteArray(inputStream);
            InputStream in = new ByteArrayInputStream(b);
            return in;
        } catch (IOException e) {
            throw new ConfigurationException(Strings.sprintf("Unable to obtain input stream for cacheManagerConfigFile [ {} ] :{}", configFile, e.getMessage()));
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

}
